package com.zkq.graduate.service.impl;

import com.zkq.graduate.mapper.SelectedTitleMapper;
import com.zkq.graduate.mapper.StudentMapper;
import com.zkq.graduate.pojo.Student;
import com.zkq.graduate.service.StudentService;
import com.zkq.graduate.util.FileUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author zhangkaiqiang
 * @Date 2019/11/29  10:48
 * @Description TODO
 */
@Service("studentService")
public class StudentServiceImpl implements StudentService {

	@Resource
	private StudentMapper studentMapper;

	@Resource
	private SelectedTitleMapper selectedTitleMapper;


	@Value("${create.design}")
	private String designPath;


	@Override
	public Optional<Student> findByStudentId(String studentID) {
		return Optional.ofNullable(studentMapper.findByStudentId(studentID));
	}

	@Override
	public boolean findStudentIfSelected(String studentId) {
		return selectedTitleMapper.findStudentIfSelected(studentId)==0;
	}

	@Override
	public Map<String,String> uploadDesign(MultipartFile file,String studentId) {
		Map<String,String> result=new HashMap<>(16);
		if(file==null){
			throw new IllegalArgumentException("上传文件为null,请进行检查");
		}

		File temp=new File(designPath);
		if(!temp.exists()){
			temp.mkdirs();
		}

		// 检测是否已经上传过毕业设计,若上传过则删除旧文件
		String fileName=file.getOriginalFilename();
		String[] last=fileName.split("\\.");
		String filePath=new StringBuilder(designPath).append(File.separator).append(studentId).append("-").append("毕业设计.").append(last[1]).toString();
		File finalFile=new File(filePath);
		if(FileUtil.ifExistsFile(designPath,filePath)){
			finalFile.delete();
		}
		try {
			file.transferTo(finalFile);
			result.put("code","0");
			result.put("msg","upload success");
			result.put("filePath",filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}


	@Override
	public boolean batchInsert(List<Map<String,String>> students){
		if(CollectionUtils.isEmpty(students)){
			return false;
		}
		return studentMapper.batchInsert(students)==students.size();
	}
}
